package com.zxtech.zzm.zxmonitorsocket.thread

import com.zxtech.zzm.core.util.DeviceUtil
import com.zxtech.zzm.zxmonitorsocket.SocketPackageSend
import com.zxtech.zzm.zxmonitorsocket.ZXMonitorSocketService
import com.zxtech.zzm.zxmonitorsocket.util.SocketLoggerUtil
import java.io.IOException
import java.io.OutputStream
import java.net.Socket

class HeartBeatThread(s: Socket) : Thread() {
  @Volatile private var stopflag = true //true 线程停止， false线程继续
  private var clientos: OutputStream? = null
  private val s: Socket?
  fun setStopFlag(stopFlag: Boolean) {
    stopflag = stopFlag
  }

  override fun run() {
    this.name = "zxmonitor_socket_heartbeat"
    SocketLoggerUtil.logSocket("线程" + this.id + "心跳线程开始")
    super.run()
    stopflag = false
    while (s != null && s.isConnected && !s.isClosed && !stopflag) {
      try {
        val builder = SocketPackageSend.Builder()
        builder.setPackageLength(byteArrayOf(0x00, 0x03))
            .setType(0x04.toByte())
            .setIdBytes(
                DeviceUtil.getTerminalID()
                    .toByteArray()
            )
            .setData(byteArrayOf(0x00, 0x00, 0x00)) //后两字节为信号强度
        ZXMonitorSocketService.sendPackage(builder)
        sleep((20 * 1000).toLong())
      } catch (e: InterruptedException) {
        e.printStackTrace()
      }
      SocketLoggerUtil.logSocket("线程" + this.id + "发送了一次心跳")
    }
    SocketLoggerUtil.logSocket("线程" + this.id + "心跳线程终止")
    stopflag = true
  }

  init {
    this.s = s
    try {
      clientos = s.getOutputStream()
    } catch (e: IOException) {
      e.printStackTrace()
    }
  }
}